# -*- encoding: utf-8 -*-
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exceptions import OperationalError
import psycopg2

import settings

def connect():
	return psycopg2.connect(
		user=settings.DB_USER,
		password=settings.DB_PASSWORD,
		database=settings.DB_DATABASE,
		host=settings.DB_HOST) 

db_engine = create_engine('postgres://', creator=connect)

class Database(object):
	'''Singleton from wikipedia :D'''
	def __new__(type, *args):
		if not '_the_instance' in type.__dict__:
			type._the_instance = object.__new__(type)
		return type._the_instance
 
	def __init__(self, metadatas=None):
		'''Initiate DB Access'''
		if not '_ready' in dir(self):
			self._ready = True
		self.engine = db_engine
		self.metadata = MetaData(self.engine)
		self.Session = scoped_session(sessionmaker(self.engine))
		self.Base = declarative_base()
